class Solution {
public:
    string reverseWords(string s) {
        int slow = 0;
        for (int fast = 0; fast < s.size(); ++fast)
        {
            if (s[fast] != ' ')
            {
                if (slow > 0) s[slow++] = ' ';
                while (fast < s.size() && s[fast] != ' ') s[slow++] = s[fast++];
            }
        }
        s.resize(slow);
        reverse(s.begin(), s.end());
        int start = 0;
        for (int end = 0; end < s.size(); ++end)
        {
            if (s[end] == ' ')
            {
                reverse(s.begin() + start, s.begin() + end);
                start = ++end;
            }
        }
        reverse(s.begin() + start, s.end());
        return s;
    }
};